#include "stdafx.h"
#include "Detail.h"
#include "List.h"
#include "FormDetail.h"

namespace wlog {

	using namespace System::Collections;
	using namespace TL_Tools;
	using namespace TL_Libs;

	Hashtable^ Detail::GetFields(void)
	{
		Hashtable^ fields = gcnew Hashtable;
		fields->Add("id_list", this->id_list);
		fields->Add("flag", this->flag);

		String^ desc = TL_Tools::Crypt::EncryptDES(this->desc, Detail::KEY);
		//String^ desc = Sqlite::safeValue(this->desc);
		fields->Add("desc", desc);
		fields->Add("day_at", this->day_at);

		this->f_req = gcnew ArrayList;
		this->f_req->Add("id_list");
		this->f_req->Add("flag");
		this->f_req->Add("day_at");

		this->VerifyFields(fields);

		return fields;
	}

	Hashtable^ Detail::GetAllByListId(int id_list)
	{
		ArrayList^ items = this->db->CreateQuery(this->ToString())
								  ->Where("id_list = ", id_list.ToString())
								  ->GetAll();
		Hashtable^ result = gcnew Hashtable;

		if (items->Count > 0)
		{
			IEnumerator^ ie = items->GetEnumerator();
			while (ie->MoveNext())
			{
				Hashtable^ item = safe_cast<Hashtable^>(ie->Current);
				String^ desc = TL_Tools::Crypt::DecryptDES(
											item["desc"]->ToString(),
											Detail::KEY
											);
				//String^ desc = item["desc"]->ToString();
				result->Add(item["flag"]->ToString(), desc);
			}
		}

		return result;
	}

	int Detail::GetIdByFlagAndListId(int id_list, String^ flag)
	{
		Hashtable^ item = this->db->CreateQuery(this->ToString())
								  ->AndWhere("id_list = ", id_list.ToString())
								  ->AndWhere("flag = ", flag)
								  ->GetRow();
		if (item->ContainsKey("id"))
		{
			return Convert::ToInt32(item["id"]);
		}
		return 0;
	}

	// Hashtable^ item = {"SUM", "sdfsdfsdf"}
	void Detail::UpdateItem(int id_list, Hashtable^ item)
	{
		int length = FormDetail::weeks_en->Length;
		List^ list = gcnew List(id_list);

		for (int i=0; i<length; ++i)
		{
			String^ flag = FormDetail::weeks_en[i];
			int id = this->GetIdByFlagAndListId(id_list, flag);

			Detail^ detail = gcnew Detail(id);
			detail->id_list = id_list.ToString();
			detail->flag = flag;

			if (item != nullptr && item->ContainsKey(flag))
			{
				detail->desc = item[flag]->ToString();
			}

			int j = 0;
			if (flag->Equals("SUM"))
			{
				j = -1;
			}

			DateTime^ day_at = DateTime::Parse(list->day_at);
			detail->day_at = day_at->AddDays(i + j).ToString(List::TFORMAT);
			detail->Save();
		}
	}

	void Detail::CleanItems(int id_list)
	{
		this->db->CreateQuery(this->ToString())
				->Delete()
				->AndWhere("id_list = ", id_list.ToString())
				->ExecuteQuery();
	}

}